<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author ThinkGem
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'shop:order:soAdvanceOrder:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #remarks="{ model, field }">
        <WangEditor
          v-model:value="model[field]"
          :bizKey="record.id"
          :bizType="'testDataChild_' + field"
          :height="300"
        />
      </template>

      <!-- <template #money>
        <div style="display: flex">
          <div style="flex: 1; display: flex">
            <div style="width: 120px; text-align: right;margin-right: 20px;">优惠金额:</div>
            <div style="width: 120px">{{ record.disMoney }}</div>
          </div>
          <div style="flex: 1; display: flex">
            <div style="width: 120px; text-align: right;margin-right: 20px;">商品总价:</div>
            <div style="width: 120px">{{ record.sumMoney }}</div>
          </div>
          <div style="flex: 1; display: flex">
            <div style="width: 120px; text-align: right;margin-right: 20px;">合计金额:</div>
            <div style="width: 120px">{{ record.payMoney }}</div>
          </div>
        </div>
        <div style="display: flex">
          <div style="flex: 1; display: flex">
            <div style="width: 120px; text-align: right;margin-right: 20px;">经销商余额:</div>
            <div style="width: 120px">{{ record.cusMoney.appZhMoney }}</div>
          </div>
          <div style="flex: 1; display: flex">
            <div style="width: 120px; text-align: right;margin-right: 20px;">经销商返利余额:</div>
            <div style="width: 120px">{{ record.cusMoney.appFlMoney }}</div>
          </div>
          <div style="flex: 1; display: flex">
            <div style="width: 120px; text-align: right;margin-right: 20px;">经销商促销余额:</div>
            <div style="width: 120px">{{ record.cusMoney.appCxMoney }}</div>
          </div>
        </div>
        <div style="display: flex">
          <div style="flex: 1; display: flex">
            <div style="width: 120px; text-align: right;margin-right: 20px;">返利金额上限:</div>
            <div style="width: 120px">{{ record.flMoneyLmit }}</div>
          </div>
          <div style="flex: 1; display: flex">
            <div style="width: 120px; text-align: right;margin-right: 20px;">促销金额上限:</div>
            <div style="width: 120px">{{ record.cxMoneyLmit }}</div>
          </div>
          <div style="flex: 1; display: flex">
            <div style="width: 120px; text-align: right;margin-right: 20px;">返利促销金额上限:</div>
            <div style="width: 120px">{{ record.sumMoneyLmit }}</div>
          </div>
        </div>
      </template> -->

      <template #testDataChildList>
        <!--  @row-click="handleTestDataChildRowClick" -->
        <BasicTable @register="registerTestDataChildTable"> </BasicTable>
        <!-- <a-button class="mt-2" @click="handleTestDataChildAdd" v-auth="'shop:order:soMain:edit'">
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button> -->
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsShopOrderSubmitForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { saveBackOrder } from '/@/api/shop/order/soMain';
  import { officeTreeData } from '/@/api/sys/office';
  import { areaTreeData } from '/@/api/sys/area';
  import { BasicUpload } from '/@/components/Upload';
  import { WangEditor } from '/@/components/WangEditor';
  import {
    orderSettleForm,
    saveFromAdvanceOrder,
    getSelectCurCus,
    findSelectMnCusListData,
  } from '/@/api/shop/order/soAdvanceOrder';

  const emit = defineEmits(['success', 'register']);

  let payMoney = ref<any>(0)

  const { t } = useI18n('shop:order:soAdvanceOrder');
  const { showMessage } = useMessage();
  const record = ref<any>({} as any);
  const getTitle = computed(() => ({
    icon: 'simple-line-icons:basket-loaded',
    value: t('提交订单'),
  }));

  // const inputFormSchemas: FormSchema[]=[]

  const [registerForm, { resetFields, setFieldsValue, getFieldsValue, validate, setProps }] =
    useForm();

  const [registerTestDataChildTable, testDataChildTable] = useTable({
    // actionColumn: {
    //   width: 60,
    //   actions: (record: Recordable) => [
    //     {
    //       icon: 'ant-design:delete-outlined',
    //       color: 'error',
    //       popConfirm: {
    //         title: '是否确认删除',
    //         confirm: handleTestDataChildDelete.bind(this, record),
    //       },
    //       auth: 'shop:order:soMain:edit',
    //     },
    //   ],
    // },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setTestDataChildTableData(_res: Recordable) {
    testDataChildTable.setColumns([
      {
        title: t('存货编码'),
        dataIndex: 'cinvcode',
        width: 130,
        align: 'left',
      },
      {
        title: t('存货名称'),
        dataIndex: 'basInv.cinvname',
        width: 240,
        align: 'left',
      },
      // {
      //   title: t('协同路线'),
      //   dataIndex: 'croute',
      //   width: 150,
      //   align: 'left',
      // },
      // {
      //   title: t('规格型号'),
      //   dataIndex: 'cinvstd',
      //   width: 130,
      //   align: 'left',

      // },
      {
        title: t('换算率'),
        // dataIndex: 'basInv.ichangrate',
        dataIndex: 'ichangerate',
        width: 80,
        align: 'center',
      },
      {
        title: t('单价'),
        dataIndex: 'appPrice',
        align: 'center',
        width: 80,
      },
      {
        title: t('总价'),
        dataIndex: 'isum',
        align: 'center',
        width: 80,
      },
      {
        title: t('数量'),
        dataIndex: 'iquantity',
        width: 130,
        align: 'center',
      },
      {
        title: t('件数'),
        dataIndex: 'inum',
        width: 130,
        align: 'center',
      },
    ]);
    // testDataChildTable.setTableData(record.value.testDataChildList || []);
    testDataChildTable.setTableData(record.value.advanceOrderChildList || []);
  }

  function handleTestDataChildRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleTestDataChildAdd() {
    testDataChildTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleTestDataChildDelete(record: Recordable) {
    testDataChildTable.deleteTableDataRecord(record);
  }

  async function getTestDataChildList() {
    let testDataChildListValid = true;
    let testDataChildList: Recordable[] = [];

    for (const record of testDataChildTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        testDataChildListValid = false;
      }
      testDataChildList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    // for (const record of testDataChildTable.getDelDataSource()) {
    //   if (!!record.isNewRecord) continue;
    //   testDataChildList.push({
    //     ...record,
    //     status: '1',
    //   });
    // }
    if (!testDataChildListValid) {
      throw { errorFields: [{ name: ['testDataChildList'] }] };
    }
    return testDataChildList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });

    await resetFields();

    const res = await orderSettleForm(data);
    record.value = res.data;
    payMoney.value = record.value.sumMoney
    let curCus = await getSelectCurCus({ code: record.value.cusCode });
    record.value.__t = new Date().getTime();
    
    let inputFormSchemas: FormSchema[] = [
      {
        label: t('客户编码'),
        field: 'cusMoney.cusCode',
        dynamicDisabled: true,
        component: 'Input',
        componentProps: {
          maxlength: 200,
        },
        colProps: { lg: 12, md: 24 },
        required: true,
      },
      {
        label: t('客户名称'),
        field: 'cusMoney.cusName',
        dynamicDisabled: true,
        component: 'Input',
        componentProps: {
          maxlength: 200,
        },
        colProps: { lg: 12, md: 24 },
        required: true,
      },
      {
        label: t('商品'),
        field: 'testDataChildList',
        component: 'Input',
        colProps: { lg: 24, md: 24 },
        slot: 'testDataChildList',
      },
      // {
      //   field: 'money',
      //   component: 'Input',
      //   colProps: { lg: 24, md: 24 },
      //   slot: 'money',
      // },
      {
        label: t('优惠金额'),
        field: 'disMoney',
        dynamicDisabled: true,
        defaultValue: '0.00',
        component: 'Input',
        componentProps: {
          maxlength: 200,
        },
        colProps: { lg: 12, md: 24 },
      },
      {
        label: t('商品总价'),
        field: 'sumMoney',
        dynamicDisabled: true,
        defaultValue: '0.00',
        component: 'Input',
        componentProps: {
          maxlength: 200,
        },
        colProps: { lg: 12, md: 24 },
      },

      {
        label: t('经销商余额'),
        field: 'cusMoney.appZhMoney',
        dynamicDisabled: true,
        defaultValue: '0.00',
        component: 'Input',
        componentProps: {
          maxlength: 200,
        },
        colProps: { lg: 12, md: 24 },
      },
      {
        label: t('合计金额'),
        field: 'payMoney',
        dynamicDisabled: true,
        defaultValue: '0.00',
        component: 'Input',
        componentProps: {
          maxlength: 200,
        },
        colProps: { lg: 12, md: 24 },
      },

      {
        label: t('经销商返利余额'),
        field: 'cusMoney.appFlMoney',
        dynamicDisabled: true,
        defaultValue: '0.00',
        component: 'Input',
        componentProps: {
          maxlength: 200,
        },
        colProps: { lg: 12, md: 24 },
      },
      {
        label: t('经销商促销余额'),
        field: 'cusMoney.appCxMoney',
        dynamicDisabled: true,
        defaultValue: '0.00',
        component: 'Input',
        componentProps: {
          maxlength: 200,
        },
        colProps: { lg: 12, md: 24 },
      },
      {
        label: t('返利金额上限'),
        field: 'flMoneyLmit',
        dynamicDisabled: true,
        defaultValue: '0.00',
        component: 'Input',
        componentProps: {
          maxlength: 200,
        },
        colProps: { lg: 12, md: 24 },
      },
      {
        label: t('促销金额上限'),
        field: 'cxMoneyLmit',
        dynamicDisabled: true,
        defaultValue: '0.00',
        component: 'Input',
        componentProps: {
          maxlength: 200,
        },
        colProps: { lg: 12, md: 24 },
      },
      {
        label: t('返利促销金额上限'),
        field: 'sumMoneyLmit',
        dynamicDisabled: true,
        defaultValue: '0.00',
        component: 'Input',
        componentProps: {
          maxlength: 200,
        },
        colProps: { lg: 12, md: 24 },
      },
      {
        field: 'Input',
        component: 'None',
        componentProps: {
          maxlength: 200,
        },
        colProps: { lg: 12, md: 24 },
      },

      {
        label: t('使用返利余额'),
        field: 'flMoney',
        component: 'InputNumber',
        defaultValue: 0,
        componentProps: {
          maxlength: 200,
          onChange(e) {
            let data = {...getFieldsValue()}
            payMoney.value  = Number(data.sumMoney) - Number(data.flMoney) - Number(data.cxMoney) - Number(data.disMoney)
            // if(Number(data.flMoney) > Number(data.flMoneyLmit)){
            //   setFieldsValue({
            //     ...getFieldsValue(),
            //     'flMoney':''
            //     })
            //   showMessage(t('使用返利余额不能超过上限！'));
            // }
            // if(Number(data.flMoney) < 0){
            //   setFieldsValue({
            //     ...getFieldsValue(),
            //     'flMoney':''
            //     })
            //   showMessage(t('使用返利余额不能为负数'));
            // }
          },
        },
        colProps: { lg: 12, md: 24 },
        rules: [
          { required: false },
          {
            validator(_rule, value) {
              return new Promise((resolve, reject) => {
                if (
                  value + Number(getFieldsValue().cxMoney) >
                  Number(getFieldsValue().sumMoneyLmit)
                ) {
                  reject(t('使用返利促销之和不能超过上限'));
                } else if (value > Number(getFieldsValue().flMoneyLmit)) {
                  reject(t('不能超过返利金额上限'));
                } else if (value < 0) {
                  reject(t('不能小于零'));
                } else {
                  resolve();
                }
              });
            },
          },
        ],
      },
      {
        label: t('使用促销余额'),
        field: 'cxMoney',
        component: 'InputNumber',
        defaultValue: 0,
        componentProps: {
          maxlength: 200,
          onChange(e) {
            let data = {...getFieldsValue()}
            payMoney.value  = Number(data.sumMoney) - Number(data.flMoney) - Number(data.cxMoney) - Number(data.disMoney)
            
            // if(Number(data.flMoney) > Number(data.flMoneyLmit)){
            //   setFieldsValue({
            //     ...getFieldsValue(),
            //     'flMoney':''
            //     })
            //   showMessage(t('使用返利余额不能超过上限！'));
            // }
            // if(Number(data.flMoney) < 0){
            //   setFieldsValue({
            //     ...getFieldsValue(),
            //     'flMoney':''
            //     })
            //   showMessage(t('使用返利余额不能为负数'));
            // }
          },
        },
        colProps: { lg: 12, md: 24 },
        rules: [
          { required: false },
          {
            validator(_rule, value) {
              return new Promise((resolve, reject) => {
                if (
                  value + Number(getFieldsValue().flMoney) >
                  Number(getFieldsValue().sumMoneyLmit)
                ) {
                  reject(t('使用返利促销之和不能超过上限'));
                } else if (value > Number(getFieldsValue().cxMoneyLmit)) {
                  reject(t('不能超过促销金额上限'));
                } else if (value < 0) {
                  reject(t('不能小于零'));
                } else {
                  resolve();
                }
              });
            },
          },
        ],
      },
      // {
      //   label: t('核发门店'),
      //   field: 'hfmdCode',
      //   component: 'ListSelect',
      //   componentProps: {
      //     selectType: 'hfmdSelec',
      //     params:{
      //       code:record.value.cusCode
      //     }
      //   },
      //   ifShow: curCus.bmn == '0' && curCus.bsjmn == '0' ? false : true,
      //   required: curCus.bmn == '1' ? true : false,
      // },
      {
        label: t('核发门店'),
        field: 'hfmdCode',
        component: 'TreeSelect',
        componentProps: {
          api: findSelectMnCusListData,
          params: {
            isLoadUser: true,
            userIdPrefix: '',
            code: record.value.cusCode,
            isShowCode: true,
            isAll: true,
          },
          canSelectParent: false,
          allowClear: true,
        },
        ifShow: curCus.bmn == '0' && curCus.bsjmn == '0' ? false : true,
        required: curCus.bmn == '1' ||  curCus.bsjmn == '1'? true : false,
        itemProps: { validateTrigger: 'blur' },
      },
      {
        label: t('备注'),
        field: 'remarks',
        component: 'InputTextArea',
        componentProps: {
          maxlength: 200,
        },
      },
    ];
    await setProps({
      labelWidth: 140,
      schemas: inputFormSchemas,
      baseColProps: { lg: 24, md: 24 },
    });
    console.log(record.value);

    setFieldsValue(record.value);
    setTestDataChildTableData(record.value);
    // setTimeout(() => {
    //   setTestDataChildTableData(record.value);
    // }, 500);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();

      // setDrawerProps({ confirmLoading: true });
      const params: any = {
        selIds: record.value.selIds,
        // id: record.value.id,
      };
      // data.soAdvanceOrderChildList = await getTestDataChildList();
      data.soAdvanceOrderChildList = await testDataChildTable.getDataSource();

      let data2 = {
        hfmdCode: data.hfmdCode ? data.hfmdCode : '',
        cusCode: data.cusMoney.cusCode,
        cusMoney: data.cusMoney,
        disMoney: data.disMoney,
        // zhMoney:this.data.zhMoney,
        // flMoney:this.data.flMoney,
        // cxMoney:this.data.cxMoney,
        // zhMoney:this.data.zhMoney,
        zhMoney: payMoney.value,
        flMoney: data.flMoney,
        cxMoney: data.cxMoney,
        sumMoney: data.sumMoney,
        payMoney: payMoney.value,
        selIds: record.value.selIds,
        // selIds:data.soAdvanceOrderChildList.map(item => item.id).join(','),
        carList: data.soAdvanceOrderChildList,
        remarks: data.remarks,
      };

      console.log('submit', params, data2, record);
      const res = await saveFromAdvanceOrder(params, data2);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
<style lang="less" scoped>
  :deep(.jeesite-editable-cell__action) {
    display: none;
  }
  /* .jeesite-editable-cell__action {
    display: none;
  } */

  :deep(.edit-cell-align-center) {
    width: 100% !important;
  }
  :deep(#sumMoneyLmit) {
    color: red;
  }
  :deep(#form_item_sumMoneyLmit) {
    color: red !important;
  }
</style>
